<?php

class UserController extends CController
{
    const PAGE_SIZE=10;

    /**
     * @var string specifies the default action to be 'list'.
     */
    public $defaultAction='list';

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            
            array('allow',  
                'users'=>array('*'),
            ),
        );
    }

    /**
     * Shows a particular model.
     */
    public function actionShow()
    {
        $this->render('show',array('model'=>$this->loadUser()));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'show' page.
     */
    public function actionCreate()
    {
        $model=new User;
        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
            if($model->save())
                $this->redirect(array('admin'));
        }
        $this->render('create',array('model'=>$model));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'show' page.
     */
    public function actionUpdate()
    {
        $model=$this->loadUser();
        if(isset($_POST['User']))
        {
            $model->attributes=$_POST['User'];
            if($model->save())
                $this->redirect(array('admin'));
        }
        $this->render('update',array('model'=>$model));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'list' page.
     */
    public function actionDelete()
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadUser()->delete();
            $this->redirect(array('list'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionList()
    {
        $criteria=new CDbCriteria;

        $pages=new CPagination(User::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $models=User::model()->findAll($criteria);

        $this->render('list',array(
            'models'=>$models,
            'pages'=>$pages,
        ));
    }

    /**
     * Manages all models.
     */
    public function processActionAdmin($view)
    {
        $this->processAdminCommand();

        $criteria=new CDbCriteria;

        //filters group for Group, City, Country, group object created explicitly
        $fromGroup = new CFilterGroup('Filter', array('cssClass'=>'dataFilterBlock'));
        $fromFilterOptions = array('emptyValue'=>'All', 'specialOptions'=>array('null'=>'None'));

        //filters group for Group and City without autosubmit, used custom view
        $filterNoAutoGroup = new CFilterGroup('Filter (no autosubmit)',
            array('view'=>'application.views.user.dataFilterGroupWithSubmit'));

        $filters = new CDataFilter(User::model());
        
        $filters->addFilter(new CFilterSearch('userFieldsSearch'), 'Search');
        $filters->addFilter(new CFilterDropdown('Group', $fromFilterOptions), $fromGroup);
        $filters->addFilter(new CFilterDropdown('Country', $fromFilterOptions), $fromGroup);
        $filters->addFilter(new CFilterDropdown('City', $fromFilterOptions), $fromGroup);

        $filters->addFilter(new CFilterDropdown('activeDropFilter',
            array('displayName'=>'Active')),
            //group is given as name (string), not as object
            //this filter will be joined to 'Filter' group, because group with same name already exists
            'Filter'
        );

        if ($view == 'admin') {
            $description = "Managing users, dropdown filters are in autosubmit mode.<br/>
            Group 'Filter (no autosubmit)' rendered using custom view,
            autosubmit disabled and added custom submit button.
            ";

            // two filters without autosubmit
            // submit button is placed in custom view (see views/user/dataFilterGroupWithSubmit.php)
            $filters->addFilter(new CFilterDropdown('groupFilter2',
                array('displayName'=>'Group', 'emptyValue'=>'All', 'specialOptions'=>array('null'=>'None'),
                    'autoSubmit'=>false)
                ), $filterNoAutoGroup
            );
            $filters->addFilter(new CFilterDropdown('countryFilter2',
                array('displayName'=>'Country', 'emptyValue'=>'All', 'specialOptions'=>array('null'=>'None'),
                    'autoSubmit'=>false)
                ), $filterNoAutoGroup
            );
        } else {
            $description = "Managing users, autosubmit mode for dropdown filters disabled.<br/>
            'Submit' and 'Reset' buttons are enabled.<br/>
            Form state saved to the session (do any filtration, go to another
            page and return back - filters state should be restored).
            ";

            //Store filter parameters to the session for 'adminNoAuto' view
            $filters->storeToSession = true;
        }
        
        // two link filters, all users is a default filter (highlighted if no other filters applied)
        $filters->addFilter(new CFilterLink('activeFilter', 'All Users', 'all', true), 'Show');
        $filters->addFilter(new CFilterLink('activeFilter', 'Active Users', 'active'), 'Show');
 
        $filters->applyCriteria($criteria);

        $pages=new CPagination(User::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort=new CSort('User');
        $sort->applyOrder($criteria);

        $models=User::model()->findAll($criteria);

        $this->render($view,compact(
            'models', 'pages', 'sort', 'filters', 'description'
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $this->processActionAdmin('admin');
    }

    /**
     * Manages all models.
     */
    public function actionAdminNoAuto()
    {
        $this->processActionAdmin('adminNoAuto');
    }


    // Action for ajax version
    // Filtered data shown using ajax requests
    public function actionAdminAjax()
    {
        $description = "Managing users, ajax mode enabled.<br/>
        Form submited via POST (just for demo purpose, 
        pagination, sorting and link filters submitted via GET).";

        $this->processAdminCommand();

        $criteria=new CDbCriteria;

        $fromGroupOptions = array('emptyValue'=>'All', 'specialOptions'=>array('null'=>'None'));

        $filters = new CDataFilter(User::model());
        $filters->addFilter(new CFilterSearch('userFieldsSearch'), 'Search');
        $filters->addFilter(new CFilterDropdown('Group', $fromGroupOptions), 'Filter');
        $filters->addFilter(new CFilterDropdown('Country', $fromGroupOptions), 'Filter');
        $filters->addFilter(new CFilterDropdown('City', $fromGroupOptions), 'Filter');
        
        $filters->addFilter(new CFilterDropdown('activeDropFilter',
                array('displayName'=>'Active')), 'Filter'
        );
        $filters->addFilter(new CFilterLink('activeFilter', 'All Users', 'all', true), 'Show');
        $filters->addFilter(new CFilterLink('activeFilter', 'Active Users', 'active'), 'Show');

        $filters->applyCriteria($criteria);

        $pages=new CPagination(User::model()->count($criteria));
        $pages->pageSize=self::PAGE_SIZE;
        $pages->applyLimit($criteria);

        $sort=new CSort('User');
        $sort->applyOrder($criteria);

        $models=User::model()->findAll($criteria);

        if (!Yii::app()->request->isAjaxRequest) {
            $this->render('adminAjax',compact(
                'models', 'pages', 'sort', 'filters', 'description'
            ));
        } else {
           $this->renderPartial('adminAjax_list', compact(
                'models', 'pages', 'sort', 'filters', 'description'
            ));
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
     */
    public function loadUser($id=null)
    {
        if($this->_model===null)
        {
            if($id!==null || isset($_GET['id']))
                $this->_model=User::model()->findbyPk($id!==null ? $id : $_GET['id']);
            if($this->_model===null)
                throw new CHttpException(404,'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Executes any command triggered on the admin page.
     */
    protected function processAdminCommand()
    {
        if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete')
        {
            $this->loadUser($_POST['id'])->delete();
            // reload the current page to avoid duplicated delete actions
            $this->refresh();
        }
    }
}
